package com.fessc.develop.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fessc.develop.entity.comvo.FileUploadBase64Vo;
import com.fessc.develop.entity.dbvo.Enclosure;
import com.fessc.develop.mapper.EnclosureMapper;
import com.fessc.develop.service.interfaces.IEnclosureService;
import com.fessc.develop.utils.BusiUtil;
import com.fessc.develop.utils.ExceptionUtil;
import com.mongodb.client.gridfs.model.GridFSFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.Base64Utils;
import org.springframework.util.StreamUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author w
 * @since 2025-04-24
 */
@Slf4j
@Service
public class EnclosureServiceImpl extends ServiceImpl<EnclosureMapper, Enclosure> implements IEnclosureService {

    @Resource
    private EnclosureMapper enclosureMapper;

    @Resource
    private GridFsTemplate gridFsTemplate;

    @Resource
    private GridFsOperations gridFsOperations;

    /**
     * @param enclosure
     * @return
     */
    @Override
    public Boolean updateUploadBankFileId(Enclosure enclosure) {
        UpdateWrapper<Enclosure> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", enclosure.getId());
        updateWrapper.set("file_id", enclosure.getFileId());
        updateWrapper.set("bank_send", enclosure.getBankSend());
        return this.update(updateWrapper);
    }

    /**
     * @param bankid
     * @param termDate
     * @return
     */
    @Override
    public List<Enclosure> getEnclosureListToBank(String bankid, String termDate) {
        return enclosureMapper.getEnclosureListToBank(bankid, termDate);
    }

    /**
     * @param settleId
     * @return
     */
    @Override
    public List<Enclosure> getEnclosureListBySettleId(String settleId) {
        QueryWrapper<Enclosure> queryWrapper = new QueryWrapper();
        queryWrapper.eq("settle_id", settleId);
        return this.list(queryWrapper);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public Enclosure getEnclosureListById(String id) {
        QueryWrapper<Enclosure> queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", id);
        return this.getOne(queryWrapper);
    }

    /**
     * @param enclosure
     * @return
     */
    @Override
    public FileUploadBase64Vo getFileUploadBase64ByMongdbid(Enclosure enclosure) throws IOException {
        FileUploadBase64Vo fileUploadVo = new FileUploadBase64Vo();
        InputStream inputStream = null;
        try {
            GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(enclosure.getMongdbId())));
            log.info("文件ID：" + gridFSFile.getObjectId() + "，名称：" + gridFSFile.getFilename() + "，大小：" + Math.round(gridFSFile.getLength()) + "KB" );
            GridFsResource resource = gridFsOperations.getResource(gridFSFile);
            inputStream = resource.getInputStream();
            //byte[] encodedBytes = StreamUtils.copyToByteArray(inputStream);
            int i = enclosure.getFileName().lastIndexOf('.');
            String fileExtension = (i != -1) ? enclosure.getFileName().substring(i + 1) : "";
            fileUploadVo.setFileFormat(BusiUtil.getFileFormat(fileExtension.toUpperCase()));
            fileUploadVo.setFileName(enclosure.getFileName());
            // 分块读取文件并进行Base64编码
            byte[] buffer = new byte[1024 * 1024];
            StringBuilder fileBase64 = new StringBuilder();
            int byteRead;
            while ((byteRead = inputStream.read(buffer)) != -1) {
                byte[] chunk = new byte[byteRead];
                System.arraycopy(buffer, 0, chunk, 0, byteRead);
                fileBase64.append(Base64Utils.encodeToString(chunk));
            }
            fileUploadVo.setFileData(fileBase64.toString());
        } catch (Exception e) {
            log.info("读取文件异常：" + e.getMessage() );
            throw ExceptionUtil.businessException("EE4004");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.info("关闭文件输出流异常：" + e.getMessage() );
                }
            }
        }
        return fileUploadVo;
    }
}
